<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/users' }">用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>

        </el-col>
      </el-row>
      <template>
        <el-table
          :data="userList"
          stripe
          style="width: 100%">
          <el-table-column
            label="#"
            type="index">
          </el-table-column>
          <el-table-column
            prop="username"
            label="用户名"
            width="180">
          </el-table-column>
          <el-table-column
            prop="mobile"
            label="手机号"
            width="180">
          </el-table-column>
          <el-table-column
            prop="email"
            label="邮箱">
          </el-table-column>
          <el-table-column
            prop="mg_state"
            label="状态">
            <!--  作用域插槽-->
            <template slot-scope="scope">
              <!--  {{scope.row}}-->
              <el-switch
                v-model="scope.row.mg_state"
                @change="handleUserState(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="190">
            <template slot-scope="scope">
              <!--  编辑按钮  -->
              <el-button type="primary" icon="el-icon-edit" size="mini"
                         @click="showEditDialog(scope.row.id)"></el-button>
              <!--  删除按钮  -->
              <el-button type="text" @click="open(scope.row.id)">
                <el-button type="danger" icon="el-icon-delete" size="mini"></el-button>
              </el-button>
              <!--  分配角色按钮  -->
              <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!--  添加用户对话框  -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible" @close="handleClose('addFormRef')">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
        <el-form-item label="用户名:" label-width="120px" prop="username">
          <el-input v-model="addForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码:" label-width="120px" prop="password">
          <el-input v-model="addForm.password" autocomplete="off" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" label-width="120px" prop="email">
          <el-input v-model="addForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号:" label-width="120px" prop="mobile">
          <el-input v-model="addForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <!--  修改用户的对话框  -->
    <el-dialog title="修改用户" :visible.sync="editUserDialog" @close="handleClose('editFormRef')">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
        <el-form-item label="用户名:" label-width="120px" prop="username">
          <el-input v-model="editForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" label-width="120px" prop="email">
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号:" label-width="120px" prop="mobile">
          <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </div>
    </el-dialog>
    <!--  分配角色的对话框  -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="30%"
      @close="handleCloseSetRole">
      <div>
        <p>当前的用户:{{userInfo.username}}</p>
        <p>当前的角色:{{userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="roleValue" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRole">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      const validateEmail = (rule, value, callback) => {
        if (value) {
          const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
          if (!regEmail.test(value)) {
            return callback(new Error('邮箱格式错误'));
          }
          // todo 验证完一定要加这个callback，遇到了坑
          callback();
        }
      };
      const validatePhone = (rule, value, callback) => {
        const regPhone = /^1[3456789]\d{9}$/;
        if (!regPhone.test(value)) {
          return callback(new Error('手机格式错误'))
        }
        callback();
      }
      return {
        input: '',
        queryInfo: {
          query: '',
          // 当前页码值
          pagenum: 1,
          // 每页多少条数据
          pagesize: 2

        },
        userList: [],
        total: 0,
        addForm: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        editForm: {},
        addFormRules: {
          username: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur'}
          ],
          email: [
            {required: true, message: '请输入邮箱', trigger: 'blur'},
            {validator: validateEmail, trigger: 'blur'}
          ],
          mobile: [
            {required: true, message: '请输入手机号', trigger: 'blur'},
            {validator: validatePhone, trigger: 'blur'}
          ],
        },
        editFormRules: {
          email: [
            {required: true, message: '请输入邮箱', trigger: 'blur'},
            {validator: validateEmail, trigger: 'blur'}
          ],
          mobile: [
            {required: true, message: '请输入手机号', trigger: 'blur'},
            {validator: validatePhone, trigger: 'blur'}
          ],
        },
        dialogFormVisible: false,
        editUserDialog: false,
        setRoleDialogVisible: false,
        userInfo: {},
        roleList: [],
        roleValue: ''
      }
    },
    created() {
      this.getUserList();
    },
    methods: {
      async getUserList() {
        const {data} = await this.$http.get('users', {params: this.queryInfo})
        console.log(data)
        if (data.meta.status === 200) {
          this.userList = data.data.users
          this.total = data.data.total
        } else {
          this.$message.error(data.meta.msg);
        }

      },
      // 监听每页总共多少条
      handleSizeChange(newSize) {
        console.log(newSize)
        this.queryInfo.pagesize = newSize
        this.getUserList()
      },
      handleCurrentChange(newPage) {
        console.log(newPage)
        this.queryInfo.pagenum = newPage
        this.getUserList()
      },
      // 监听switch开关的变化
      async handleUserState(userinfo) {
        console.log(userinfo)
        const {data} = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
        console.log(data)
        if (data.meta.status === 200) {
          this.$message({
            message: '修改成功',
            type: 'success'
          });
        } else {
          userinfo.mg_state = !userinfo.mg_state
          return this.$message.error('更新状态失败');
        }
      },
      // 关闭表单，使数据重置,记得传参是对应的ref
      handleClose(formName) {
        console.log(this.$refs[formName])
        this.$refs[formName].resetFields()
      },
      // 提交表单，并进行数据验证
      addUser() {
        this.$refs.addFormRef.validate(async (valid) => {
          if (!valid) return;
          const {data} = await this.$http.post('users', this.addForm)
          console.log(data)
          if (data.meta.status === 201) {
            // 添加用户成功，隐藏对话框
            this.dialogFormVisible = false
            // 重新加载userList数据
            this.getUserList()
            return this.$message.success('添加用户成功');
          } else {
            return this.$message.error('添加用户失败');
          }
        })
      },
      // 显示编辑表单里的数据
      async showEditDialog(id) {
        this.editUserDialog = true;
        console.log(id)
        const {data} = await this.$http.get(`users/${id}`)
        console.log(data)
        if (data.meta.status === 200) {
          this.editForm = data.data
        } else {
          return this.$message.error('获取用户信息失败');
        }
      },
      // 编辑用户
      editUser() {
        this.$refs.editFormRef.validate(async (valid) => {
          if (!valid) return;
          const {id, email, mobile} = this.editForm
          const {data} = await this.$http.put(`users/${id}`, {email, mobile})
          console.log(data)
          if (data.meta.status === 200) {
            // 添加用户成功，隐藏对话框
            this.editUserDialog = false
            // 重新加载userList数据
            this.getUserList()
            return this.$message.success('更新用户成功');
          } else {
            return this.$message.error('更新用户失败');
          }
        })
      },
      // 确认删除对话框
      open(id) {
        this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data} = await this.$http.delete(`users/${id}`)
          console.log(data)
          if (data.meta.status === 200) {
            //删除成功，重新加载用户列表
            this.getUserList()
            return this.$message({
              type: 'success',
              message: '删除成功!'
            });
          } else {
            return this.$message.error('更新用户失败');
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      async setRole(role) {
        // 点击分配角色，弹出对话框
        this.setRoleDialogVisible = true

        // 把这行的数据赋值给userinfo
        this.userInfo = role

        // 调用获取角色列表的接口
        const {data} = await this.$http.get('roles')
        console.log(data)
        if (data.meta.status === 200) {
          this.roleList = data.data
        } else {
          return this.$message.error('获取角色失败')
        }
      },

      // 点击确定 分配角色
      async allotRole() {
        // 获取用户id
        const userId = this.userInfo.id;
        // 获取即将分配的角色id
        const roleId = this.roleValue;
        if (!roleId) {
          return this.$message.error('请选择要分配的角色')
        }
        // 调用分配角色的接口
        const {data} = await this.$http.put(`users/${userId}/role`, {rid: roleId})
        if (data.meta.status === 200) {
          // 关闭弹框
          this.setRoleDialogVisible = false
          // 重新加载用户列表
          this.getUserList()
          // 返回成功的信息
          this.$message.success('分配角色成功')
        } else {
          return this.$message.error('分配角色失败')
        }

      },
      handleCloseSetRole() {
        this.roleValue = ''
        this.userInfo = {}
      }
    }
  }
</script>

<style lang="less" scoped>
  .el-card {
    margin-top: 10px;
  }

  .el-pagination {
    margin-top: 15px;
  }
</style>
